package com.jiaquyun.jcps.mode.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.jiaquyun.jcps.app.AppConstance
import com.jiaquyun.jcps.mode.BaseViewModel
import com.jiaquyun.jcps.entity.UserInfoResponse
import com.jiaquyun.jcps.mode.manager.AccessManager
import com.lemlin.network.HttpServiceData
import com.lemlin.network.HttpServiceResponse
import com.lemlin.network.ViewModelSubscribe
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

class AccessViewModel(application: Application) : BaseViewModel(application) {

    private val accessManager: AccessManager = AccessManager()


    val downTimeListData = MutableLiveData<Long>()

    /**
     * 验证码倒计时
     */
    fun createCodeDownTime() {
        val disposable: Disposable =
            Flowable.intervalRange(1, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe {
                    downTimeListData.postValue(-1L)
                }
                .subscribe {
                    downTimeListData.postValue((60 - it))
                }
        dispose.add(disposable)
    }


    val userInfoDataLiveData = MutableLiveData<HttpServiceResponse<UserInfoResponse>>()

    /**
     * 手机号登录
     */
    fun mobileLogin(mobile: String, captcha: String) {
        val listener = object : ViewModelSubscribe<UserInfoResponse>(userInfoDataLiveData) {
            override fun onSuccess(resp: UserInfoResponse) {
                super.onSuccess(resp)
                SPStaticUtils.put(AppConstance.BUNDLE_USER_INFO, GsonUtils.toJson(resp.data))
                SPStaticUtils.put(AppConstance.BUNDLE_USER_TOKEN, resp.data.userinfo.token)
            }
        }
        val disposable: Disposable = accessManager.mobileLogin(mobile, captcha, listener)
        dispose.add(disposable)
    }

    val baseLiveData = MutableLiveData<HttpServiceResponse<HttpServiceData>>()
    /**
     * 获取验证码
     */
    fun smsSend(mobile: String) {
        val listener = object : ViewModelSubscribe<HttpServiceData>(baseLiveData) {
            override fun onSuccess(resp: HttpServiceData) {
                super.onSuccess(resp)
            }
        }
        val disposable: Disposable = accessManager.smsSend(mobile, listener)
        dispose.add(disposable)
    }

    /**
     *
     * */

}